<?php

/**
 * 客服消息接口
 * Class CustomService
 * 客服消息开发文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140547
 * (请求和返回都在这里, 请仔细阅读, 在文档中不在赘述)
 * @author lilei<LL_strive@163.com> 2017-07-19
 */
class CustomService {

    /**
     * 客服接口-发消息
     * https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN
     *
     * @param $cid
     * * @param $mediaId
     * @param $replyMsg
     * @return mixed
     */
    public static function customSend($cid, $mediaId, $replyMsg)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=';

        if ($replyMsg->msgType == 'text') {
            /**
                {
                    "content": "再来一个文本",
                    "fromUserName": "gh_e86a027dc440",
                    "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                    "createTime": 1501145129,
                    "msgType": "text",
                    "funcFlag": 0
                }
             */
            $message = [
                'touser'    => $replyMsg->toUserName,
                'msgtype'   => 'text',
                'text'      => [
                    'content'   => $replyMsg->content
                ]
            ];
        } else if ($replyMsg->msgType == 'image') {
            /**
                {
                    "content": "",
                    "fromUserName": "gh_e86a027dc440",
                    "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                    "createTime": 1501208121,
                    "msgType": "image",
                    "funcFlag": 0,
                    "media_id": "19apvY0Op9dSdSQg0qNkDN7cVkym_1o-Rytu4UFcUVQ"
                }
             */
            $message = [
                'touser'    => $replyMsg->toUserName,
                'msgtype'   => 'image',
                'image'      => [
                    'media_id'   => $replyMsg->media_id
                ]
            ];
        } else if ($replyMsg->msgType == 'news') {
            /**
                {
                    "articles": [
                        {
                            "title": "ll",
                            "description": {},
                            "picUrl": "http://mmbiz.qpic.cn/mmbiz_jpg/oFtxYw8LmCmDlBp9KsbROlrmLSPUfk5YAmGqXE8EXpBdb48iaVoDE53upw3Z0qqcnzFyDBzrne42iakpMkAKy9Zw/0",
                            "content": {},
                            "url": ""
                        },
                        {
                            "title": "ll",
                            "description": {},
                            "picUrl": "http://mmbiz.qpic.cn/mmbiz_jpg/oFtxYw8LmCmDlBp9KsbROlrmLSPUfk5YAmGqXE8EXpBdb48iaVoDE53upw3Z0qqcnzFyDBzrne42iakpMkAKy9Zw/0",
                            "content": {},
                            "url": ""
                        }
                    ],
                    "fromUserName": "gh_e86a027dc440",
                    "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                    "createTime": 1501208121,
                    "msgType": "news",
                    "funcFlag": 0
                }
             */
            $articles = [];
            foreach ($replyMsg->articles as $a_k => $a_v) {

                $a_v = json_decode(json_encode($a_v), TRUE);
                $article = [
                    'title'         => $a_v['title'],
                    'description'   => $a_v['description'][0],
                    'url'           => $a_v['url'],
                    'picurl'        => $a_v['picUrl']
                ];
                array_push($articles, $article);
            }
            $message = [
                'touser'    => $replyMsg->toUserName,
                'msgtype'   => 'news',
                'news'      => [
                    'articles'  => $articles
                ]
            ];
        } else if ($replyMsg->msgType == 'voice') {
            /**
                {
                    "content": "",
                    "fromUserName": "gh_e86a027dc440",
                    "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                    "createTime": 1501226867,
                    "msgType": "voice",
                    "funcFlag": 0,
                    "media_id": "19apvY0Op9dSdSQg0qNkDPP7nqV-VOlJJ_1JoLSywN0"
                }
             */
            $message = [
                'touser'    => $replyMsg->toUserName,
                'msgtype'   => 'voice',
                'voice'     => [
                    'media_id'   => $replyMsg->media_id
                ]
            ];
        } else if ($replyMsg->msgType == 'video') {
            /**
             *
             */
            $message = [
                'touser'    => $replyMsg->toUserName,
                'msgtype'   => 'video',
                'video'     => [
                    'media_id'          => $replyMsg->media_id,
                    'thumb_media_id'    => '',
                    'title'             => '',
                    'description'       => ''
                ]
            ];
        }

        $result = self::csCurl($cid, $mediaId, $url, 'POST', $message, FALSE);
        return $result;
        // {"errcode":0,"errmsg":"ok"}
    }

    /*
    |--------------------------------------------------------------------------
    |                           以下为该类私有方法
    |--------------------------------------------------------------------------
    */

    /**
     * curl请求调用微信接口
     *
     * @param int    $cid
     * @param int    $mediaId
     * @param string $url            请求相应的微信接口URL
     * @param string $requestMode    HTTP请求方式[GET|POST|...]
     * @param array  $message        目前为POST请求方式下的数据
     * @param bool   $printErr       此期间, 如果有错误是否输出至页面(主要是获取TOKEN时错误)
     * @return mixed|void
     * curl中文文档: http://php.net/manual/zh/function.curl-setopt.php
     */
    private function csCurl($cid, $mediaId, $url, $requestMode, $message = array(), $printErr = FALSE)
    {
        /** 0. 获得请求微信的TOKEN */
        $accessToken = WeixinApi::getAccessToken($printErr, $cid, null, $mediaId);
        if (!$accessToken) {
            return;
        }

        $url = $url . $accessToken;
        /** 1. 初始化, 新建一个curl资源 */
        $ch = curl_init() ;

        /** 2. 设置URL和相应的选项 */
        // 2.1 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。
        curl_setopt($ch, CURLOPT_URL, $url);
        // 2.2 启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 2.3 请求方式
        switch (strtoupper($requestMode)) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, 1);
                break;
            case 'GET':
                break;
            default:
                break;
        }
        // 2.4 如果是POST请求方式, 设置post的值
        if (strtoupper($requestMode) == 'POST') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message, JSON_UNESCAPED_UNICODE));
        }
        // 2.5 FALSE 禁止 cURL 验证对等证书（peer's certificate）
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        // 2.6 公用名检查: [0|1|2(默认)]
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // 2.7 TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // 2.8 允许 cURL 函数执行的最长秒数。
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);

        /** 3. 执行CURL操作 */
        // 3.1 抓取URL并把它传递给浏览器
        $result = curl_exec($ch);
        // 3.2 抓取URL出现错误的情况
        $error = curl_errno($ch);
        if ($error) {
            \Log::write('CustomeService::csCurl()' . json_encode($error));
        }

        /** 4. 关闭cURL资源，并且释放系统资源 */
        curl_close($ch);

        /** 5. 返回结果 */
        $result = json_decode($result);
        \Log::write('CustomeService::csCurl()=>result' . json_encode($result));
//        return $result;
    }

}
